package com.cloudkinto.service.invoice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.dao.CompanyDao;
import com.cloudkinto.entity.CompanyDo;
import com.cloudkinto.entity.InvoiceRecordDo;
import com.cloudkinto.entity.InvoiceTitleDo;
import com.cloudkinto.dao.InvoiceTitleDao;
import com.cloudkinto.extentity.InvoiceTitleOweDto;
import com.cloudkinto.service.invoice.InvoiceRecordService;
import com.cloudkinto.service.invoice.InvoiceTitleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.invoice.vo.InvoiceTitleAddReq;
import com.cloudkinto.service.invoice.vo.InvoiceTitleDetailRes;
import com.cloudkinto.service.invoice.vo.InvoiceTitleOweDetailRes;
import com.cloudkinto.service.invoice.vo.InvoiceTitleUpdateReq;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author hjy
 * @since 2021-07-13
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class InvoiceTitleServiceImpl extends ServiceImpl<InvoiceTitleDao, InvoiceTitleDo> implements InvoiceTitleService {
    @Autowired
    private InvoiceTitleDao dao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private InvoiceRecordService invoiceRecordService;

    @Override
    public SingleResult addInit() {
        Map map = new HashMap();
        return SingleResult.success("");
    }

    @Override
    public InvoiceTitleAddReq add(InvoiceTitleAddReq req, Long userId, Long companyId) {
        InvoiceTitleDo entityDo = new InvoiceTitleDo();
        Integer count = dao.selectCount(new QueryWrapper<InvoiceTitleDo>().eq("tax_number", req.getTaxNumber()));
        if (count > 0)
            throw new BizExceptionI18(SysConstant.Invoice_Number_Has_Existed, req.getInvoiceTitle(), req.getTaxNumber());
        BeanUtils.copyProperties(req, entityDo);
        if (entityDo.getCompanyId() == null || entityDo.getCompanyId() == 0) {
            entityDo.setCompanyId(companyId);
        }
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
        return req;
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(InvoiceTitleDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(InvoiceTitleDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success(detail(id));
    }

    @Override
    public InvoiceTitleAddReq update(InvoiceTitleUpdateReq req, Long userId) {
        InvoiceTitleDo entityDo = dao.selectById(req.getId());
        if (entityDo == null) {
            throw new BizExceptionI18("no.order.info");
        }
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return req;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(InvoiceTitleDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(InvoiceTitleDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        InvoiceTitleDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);

        //判断这个抬头是否在使用中 固定月开
        CompanyDo companyDo = companyDao.selectOne(new LambdaQueryWrapper<CompanyDo>()
                .eq(CompanyDo::getLastInvoiceType, 0)
                .eq(CompanyDo::getLastInvoiceTitleId, id)
                .last(" order by id desc limit 1"));
        if (companyDo != null) {
            throw new BizExceptionI18(SysConstant.Invoice_Title_Used_Cannot_Delete);
        }
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(InvoiceTitleDo entityDo, Long userId) {
//        entityDo.setDeleteBy(userId);
//        entityDo.setDeleteTime(new Date());
    }

    @Override
    public InvoiceTitleDetailRes detail(Long id) {
        InvoiceTitleDo entityDo = dao.selectById(id);
        InvoiceTitleDetailRes res = new InvoiceTitleDetailRes();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<InvoiceTitleDetailRes> getList(Map<String, String> map) {
        QueryWrapper<InvoiceTitleDo> wrapper = queryBuild(map);
        List<InvoiceTitleDo> list = this.list(wrapper);
        List<InvoiceTitleDetailRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        IPage<InvoiceTitleDo> page = pageInit(map);
        List<InvoiceTitleDo> pageList = dao.listPage(page, map);
        List<InvoiceTitleDetailRes> resList = handlerListAfter(pageList);
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<InvoiceTitleDetailRes> handlerListAfter(List<InvoiceTitleDo> list) {
        List<InvoiceTitleDetailRes> result = new ArrayList<>();
        for (InvoiceTitleDo et : list) {
            InvoiceTitleDetailRes res = new InvoiceTitleDetailRes();
            BeanUtils.copyProperties(et, res);
            result.add(res);
        }
        return result;
    }

    private IPage<InvoiceTitleDo> pageInit(Map<String, String> map) {
        IPage<InvoiceTitleDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<InvoiceTitleDo> queryBuild(Map<String, String> map) {
        QueryWrapper<InvoiceTitleDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.and(invoiceRecordDoQueryWrapper -> invoiceRecordDoQueryWrapper.like("invoice_title", map.get("keyword"))
                    .or().like("bank", map.get("keyword")));
        }
        return wrapper;
    }

    @Override
    public List<InvoiceTitleOweDetailRes> oweList(Map<String, String> map) {
        List<InvoiceTitleOweDto> invoiceTitleOweDtos = dao.selectOweList(map);
        List<InvoiceTitleOweDetailRes> list = invoiceTitleOweDtos.stream().map(dto -> {
            InvoiceTitleOweDetailRes res = new InvoiceTitleOweDetailRes();
            BeanUtils.copyProperties(dto, res);
            if (dto.getInvoiceCount() > dto.getRechargeCount()) {
                InvoiceRecordDo recordServiceOne = invoiceRecordService.getOne(new LambdaQueryWrapper<InvoiceRecordDo>()
                        .eq(InvoiceRecordDo::getTaxNumber, dto.getTaxNumber()).orderByDesc(InvoiceRecordDo::getId)
                        .last("limit 1"));
                if (recordServiceOne != null && recordServiceOne.getInvoiceAmount() != null)
                    res.setOweAmount(recordServiceOne.getInvoiceAmount());
            }
            return res;
        }).sorted(new Comparator<InvoiceTitleOweDetailRes>() {
            @Override
            public int compare(InvoiceTitleOweDetailRes o1, InvoiceTitleOweDetailRes o2) {
                return (int) (o2.getOweAmount()-o1.getOweAmount());
            }
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<Map> selectInvoiceListInit(Long companyId) {
        List<Map> invoiceList = new ArrayList<>();
        List<InvoiceTitleDo> invoiceTitleDos = dao.selectList(new QueryWrapper<InvoiceTitleDo>().eq("company_id", companyId).orderByDesc("id"));
        if (!CollectionUtils.isEmpty(invoiceTitleDos)) {
            for (InvoiceTitleDo et : invoiceTitleDos) {
                Map map = new HashMap();
                map.put("id", et.getId());
                map.put("invoiceTitle", et.getInvoiceTitle());
                map.put("taxNumber", et.getTaxNumber());
                map.put("companyAddress", et.getCompanyAddress());
                invoiceList.add(map);
            }
        }
        return invoiceList;
    }

}
